using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using WorkFlowCore.BusinessDemo.Web.Data;
using WorkFlowCore.BusinessDemo.Web.Entities;
using WorkFlowCore.BusinessDemo.Web.Models;
using WorkFlowCore.BusinessDemo.Web.Services.Adapters; // Added
using WorkFlowCore.BusinessDemo.Web.Models.AdapterDtos; // Added
using System.Collections.Generic; // Added

namespace WorkFlowCore.BusinessDemo.Web.Controllers
{
    public class WorkTaskStateInfoController : BaseController
    {
        private readonly BusinessDemoDbContext _context;
        private readonly IWorkTaskAdapterService _workTaskAdapterService; // Added

        public WorkTaskStateInfoController(BusinessDemoDbContext context, IWorkTaskAdapterService workTaskAdapterService) // Modified
        {
            _context = context;
            _workTaskAdapterService = workTaskAdapterService; // Added
        }

        // 工作任务状态列表
        public async Task<IActionResult> Index(int page = 1, int pageSize = 20)
        {
            var pagedResult = await GetPagedTasks(page, pageSize);
            return View(pagedResult);
        }

        [HttpGet]
        public async Task<PagedResult<WorkTaskStateInfoViewModel>> GetPagedTasks(int page = 1, int pageSize = 20)
        {
            var query = _context.WorkTaskStateInfos
                .OrderByDescending(t => t.UpdatedTime)
                .AsQueryable();

            var totalCount = await query.CountAsync();
            
            var items = await query
                .OrderByDescending(t=>t.Id)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(t => new WorkTaskStateInfoViewModel
                {
                    Id = t.Id,
                    EntityFullName = t.EntityFullName,
                    EntityKeyValue = t.EntityKeyValue,
                    WorkTaskStatus = t.WorkTaskStatus,
                    ProcessName = t.ProcessName,
                    UpdatedTime = t.UpdatedTime
                })
                .ToListAsync();

            return new PagedResult<WorkTaskStateInfoViewModel>
            {
                TotalCount = totalCount,
                PageIndex = page,
                PageSize = pageSize,
                Items = items
            };
        }

        [HttpPost("api/worktask/state-change")]
        public async Task<IActionResult> HandleStateChange(
            [FromQuery(Name = "key")] string authKey,
            [FromBody] TaskStateChangeEventData eventData)
        {
            const string staticKey = "WF_2025_SECRET";
            if (authKey != staticKey) 
            {
                return Unauthorized(new { Message = "无效的认证密钥" });
            }

            var entityFullNames = new[] { "OfficialSealApplication"};
            
            if (eventData == null || eventData.WorkTask == null || !entityFullNames.Contains(eventData.WorkTask.EntityFullName))
            {
                return BadRequest(new { Message = "无效的事件数据" });
            }

            var entityFullName = eventData.WorkTask?.EntityFullName;
            var entityKeyValue = eventData.WorkTask?.EntityKeyValue?.ToString();
            
            // 检查是否已存在相同entity的记录
            var existingState = await _context.WorkTaskStateInfos
                .FirstOrDefaultAsync(s => 
                    s.EntityFullName == entityFullName && 
                    s.EntityKeyValue == entityKeyValue);

            if (existingState != null)
            {
                // 更新现有记录
                existingState.WorkTaskStatus = eventData.NewWorkTaskStatus;
                existingState.UpdatedTime = DateTime.Now;
                if(string.IsNullOrWhiteSpace(existingState.ProcessName) || existingState.ProcessName == "null")
                {
                    existingState.ProcessName = eventData.WorkTask?.Name ?? "null";
                }
            }
            else
            {
                // 新增记录
                var stateInfo = new WorkTaskStateInfo
                {
                    EntityFullName = entityFullName,
                    EntityKeyValue = entityKeyValue,
                    WorkTaskStatus = eventData.NewWorkTaskStatus,
                    ProcessName = eventData.WorkTask?.Name ?? "null", // 预留字段，暂赋null
                    UpdatedTime = DateTime.Now,
                    CreatedTime = DateTime.Now,
                    CreatedUserId = CurrentEmployeeNumber, // 预设创建用户ID为system
                };
                _context.WorkTaskStateInfos.Add(stateInfo);
            }

            await _context.SaveChangesAsync();
            
            return Ok(new { 
                StateId = existingState?.Id ?? _context.Entry(_context.WorkTaskStateInfos.Local.Last()).Entity.Id 
            });
        }

        // GET: WorkTaskStateInfo/ApiDoc
        public IActionResult ApiDoc()
        {
            return View();
        }

        // GET: WorkTaskStateInfo/SyncAllStatesDoc
        public IActionResult SyncAllStatesDoc()
        {
            return View();
        }

        // 查看详情
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var workTaskStateInfo = await _context.WorkTaskStateInfos
                .FirstOrDefaultAsync(m => m.Id == id);
                
            if (workTaskStateInfo == null)
            {
                return NotFound();
            }

            var viewModel = new WorkTaskStateInfoViewModel
            {
                Id = workTaskStateInfo.Id,
                EntityFullName = workTaskStateInfo.EntityFullName,
                EntityKeyValue = workTaskStateInfo.EntityKeyValue,
                WorkTaskStatus = workTaskStateInfo.WorkTaskStatus,
                ProcessName = workTaskStateInfo.ProcessName,
                UpdatedTime = workTaskStateInfo.UpdatedTime
            };

            return View(viewModel);
        }

        public async Task<IActionResult> SyncAllStates()
        {
            try
            {
                // 1. 从数据库查询所有 WorkTaskStatus != Processed 的记录
                var statesToSync = await _context.WorkTaskStateInfos
                    .Where(s => s.WorkTaskStatus != Entities.WorkTaskStatus.Processed) // 使用 Entities.WorkTaskStatus
                    .ToListAsync();

                if (!statesToSync.Any())
                {
                    TempData["InfoMessage"] = "没有需要同步的状态记录。";
                    return RedirectToAction(nameof(Index));
                }

                // 2. 按 EntityFullName 分组
                var groupedStates = statesToSync.GroupBy(s => s.EntityFullName);

                var updatedCount = 0;
                var createdCount = 0;

                foreach (var group in groupedStates)
                {
                    var entityFullName = group.Key;
                    var entityKeyValues = group.Select(s => s.EntityKeyValue).Distinct().ToList();

                    // 3. 如果 EntityKeyValues 列表为空，则跳过
                    if (!entityKeyValues.Any())
                    {
                        continue;
                    }

                    // 4. 构造 DTO 并调用服务
                    var inputDto = new GetAllProcessingWorkTasksByEntityTypeInputDto
                    {
                        EntityFullName = entityFullName,
                        EntityKeyValues = entityKeyValues
                    };
                    
                    List<Models.AdapterDtos.WorkTaskDto> latestTasks = await _workTaskAdapterService.GetAllProcessingWorkTasksByEntityTypeAsync(inputDto);

                    if (latestTasks != null && latestTasks.Any())
                    {
                        foreach (var taskDto in latestTasks)
                        {
                            var existingState = await _context.WorkTaskStateInfos
                                .FirstOrDefaultAsync(s => s.EntityFullName == taskDto.EntityFullName && s.EntityKeyValue == taskDto.EntityKeyValue);

                            if (existingState != null)
                            {
                                // 5. 更新现有记录
                                bool changed = false;
                                var newStatusFromDto = (Entities.WorkTaskStatus)taskDto.workTaskStatus;
                                if (existingState.WorkTaskStatus != newStatusFromDto)
                                {
                                    existingState.WorkTaskStatus = newStatusFromDto;
                                    changed = true;
                                }
                                if (existingState.ProcessName != taskDto.Name)
                                {
                                    existingState.ProcessName = taskDto.Name;
                                    changed = true;
                                }

                                if (changed)
                                {
                                    existingState.UpdatedTime = DateTime.Now;
                                    updatedCount++;
                                }
                            }
                            else
                            {
                                // 6. 创建新记录
                                var newStateInfo = new Entities.WorkTaskStateInfo
                                {
                                    EntityFullName = taskDto.EntityFullName,
                                    EntityKeyValue = taskDto.EntityKeyValue,
                                    WorkTaskStatus = (Entities.WorkTaskStatus)taskDto.workTaskStatus,
                                    ProcessName = taskDto.Name,
                                    UpdatedTime = DateTime.Now,
                                    CreatedTime = DateTime.Now,
                                    CreatedUserId = CurrentEmployeeNumber
                                };
                                _context.WorkTaskStateInfos.Add(newStateInfo);
                                createdCount++;
                            }
                        }
                    }
                }

                // 7. 保存更改
                if (updatedCount > 0 || createdCount > 0)
                {
                    await _context.SaveChangesAsync();
                    TempData["SuccessMessage"] = $"同步完成：更新了 {updatedCount} 条记录，新增了 {createdCount} 条记录。";
                }
                else
                {
                    TempData["InfoMessage"] = "没有状态发生变化或需要新增的记录。";
                }
            }
            catch (Exception ex)
            {
                // 在实际应用中，这里应该使用更完善的日志记录机制
                Console.WriteLine(ex.ToString()); // 临时日志输出
                TempData["ErrorMessage"] = "同步过程中发生错误，请稍后重试或联系管理员。";
            }
            
            return RedirectToAction(nameof(Index));
        }
    }
}
